﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Janus.Cores.IOC
{
    /// <summary>
    /// IOC 容器
    /// </summary>
    public static class Container
    {
        const string UNITY_SECTION = "mes";

        static Container()
        {
            Current = new UnityContainer();
            try
            {
                Current.LoadConfiguration(UNITY_SECTION);
                string configFile = "Unity.config";
                var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
                //从config文件中读取配置信息
                System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                //获取指定名称的配置节
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                //载入名称为FirstClass 的container节点
                Current.LoadConfiguration(section);
            }
            catch (System.Configuration.ConfigurationErrorsException ce)
            {
                throw new System.Configuration.ConfigurationErrorsException("Unity配置错误，请确认配置文件中存在Unity配置节", ce);
            }
            catch (ArgumentNullException)
            {
            }
            catch
            {
                throw;
            }

        }

        /// <summary>
        /// 创建一个子容器
        /// </summary>
        /// <returns></returns>
        public static IUnityContainer CreateChildContainer()
        {
            return Current.CreateChildContainer();
        }

        /// <summary>
        /// 创建一个新的容器
        /// </summary>
        /// <returns></returns>
        public static IUnityContainer CreateContainer()
        {
            return new UnityContainer();
        }

        /// <summary>
        /// Unity容器<see cref="Microsoft.Practices.Unity.IUnityContainer"/>
        /// </summary>
        public static IUnityContainer Current
        {
            get;
            private set;
        }
    }
}
